package fr.sportsurbains;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fr.sportsurbains.reader.TopicsReader;
import fr.sportsurbains.tools.BitmapManager;
import fr.sportsurbains.tools.DBManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SearchView.OnSuggestionListener;
import android.widget.SimpleAdapter.ViewBinder;

@SuppressLint("HandlerLeak")
public class SearchActivity extends Activity implements OnQueryTextListener, OnSuggestionListener {

	TopicsReader tr;
	Handler handler;
	ProgressDialog progressDialog;
	DBManager dbmanager;
	BitmapManager bmpManager;
	List<Map<String,String>> topics;
	SimpleAdapter adp;
	InputMethodManager imm;
	SearchView search;
	ViewBinder vb = new ViewBinder() {

		@Override
		public boolean setViewValue(  
                View view,   
                Object data,    
             String textRepresentation) {    
	        //判断是否为我们要处理的对象    
	        if(view instanceof ImageView  && data instanceof String){ 
	            ImageView iv = (ImageView) view;    
	            bmpManager.loadBitmap((String)data, iv);
	            return true;    
	        }else if(view.getId() == R.id.topic) {
	        	view.setTag(data);
	        	return true;
	        }else    return false;    
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search);
		search = (SearchView) this.findViewById(R.id.search_bar);
		search.setOnQueryTextListener(this);
		search.setOnSuggestionListener(this);
		initView();
	}
	
	private void initView() {
		dbmanager = new DBManager(this);
		bmpManager = new BitmapManager(BitmapFactory.decodeResource(getResources(), R.drawable.loading17), dbmanager);
		topics = new ArrayList<Map<String,String>>();
		adp = new SimpleAdapter(this,topics,R.layout.topic,new String[]{"link","title","image","summary"},
				new int[]{R.id.topic,R.id.topic_title,R.id.topic_picture,R.id.topic_summary});
		adp.setViewBinder(vb);
		ListView lv = (ListView) this.findViewById(R.id.search_list);
		lv.setAdapter(adp);
		lv.setOnItemClickListener(new MyOnItemClickListener());
		progressDialog = new ProgressDialog(SearchActivity.this);
		progressDialog.setTitle(getResources().getString(R.string.progressdialog_title));
		progressDialog.setMessage(getResources().getString(R.string.progressdialog_message));
		handler = new Handler() {
			@SuppressLint("HandlerLeak")
			@Override
			public void handleMessage (Message msg) {
				switch(msg.what) {
				case 0: progressDialog.show();break;
				case 1: progressDialog.hide();
					outputListView();
					break;
				}					
			}
		};
		imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
	}
	
	private void outputListView() {
		// TODO Auto-generated method stub
		List<Map<String,String>> list = tr.getTopics();
		if(list.isEmpty()) {
			Map<String,String> empty = new HashMap<String,String>();
			empty.put("title", getResources().getString(R.string.no_results));
			list.add(empty);
			topics.clear();
			topics.addAll(list);
			adp.notifyDataSetChanged();
		} else {
			topics.clear();
			topics.addAll(list);
			adp.notifyDataSetChanged();
		}
	}
	
	class MyOnItemClickListener implements ListView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			if(arg1.getTag() != null) {
				/*Intent it = getIntent();
				it.setClass(SearchActivity.this, WebActivity.class);
				Bundle bd = new Bundle();
				bd.putString("link", (String)arg1.getTag());
				it.putExtras(bd);
				startActivity(it);*/
				Intent tint = new Intent(Intent.ACTION_VIEW,Uri.parse((String)arg1.getTag()));
				startActivity(tint);
			}
			
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {//捕捉返回键
        if(keyCode == KeyEvent.KEYCODE_BACK){
        	progressDialog.dismiss();
        	this.finish();
        	return true; 
        }   
        return super.onKeyDown(keyCode, event);   
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	@Override
	public boolean onSuggestionClick(int arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onSuggestionSelect(int position) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// TODO Auto-generated method stubr
		if (imm.isActive()) {
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
			}
		search.clearFocus();
		String keyword = TextUtils.join("+", TextUtils.split(query, " "));
		final String url = "http://www.sportsurbains.fr/?s="+keyword;
		new Thread() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
					try {
						tr = new TopicsReader(url);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				handler.sendEmptyMessage(1);
			}
		}.start();
		return true;
	}

}
